package com.pm.web.controller.buglist;


import com.alibaba.fastjson2.JSONObject;
import com.pm.buglist.domain.SysFiles;
import com.pm.buglist.service.SysFilesService;
import com.pm.common.annotation.Log;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.page.TableDataInfo;
import com.pm.common.enums.BusinessType;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 系统文件表 前端控制器
 * </p>
 *
 * @author wwm
 * @since 2023-12-14
 */
@RestController
@RequestMapping("/business/sys-files")
public class SysFilesController extends BaseController {

    @Resource
    private SysFilesService sysFileService;

    /**
     * 查询文件列表的接口
     * @param sysFiles
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo queryList(SysFiles sysFiles){
        startPage();
        List<SysFiles> files = sysFileService.selectFileList(sysFiles);
        return getDataTable(files);
    }

    /**
     * 文件上传接口
     * @param file 上传的文件
     * @param type 文件用途（0：头像图片，1：办公文件）
     * @return
     */
    @Log(title = "文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, String type, String remarks){
        return sysFileService.FileUpload(file,type,remarks);
    }


    /**
     * 通用文件上传接口
     * @param file 上传的文件
     * @return
     */
    @Log(title = "文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload/other")
    public AjaxResult uploadOtherFile(@RequestParam("file") MultipartFile file){
        return sysFileService.fileUploadOther(file);
    }




    /**
     * 根据文件id查询文件信息
     * @param id Long
     * @return
     */
    @GetMapping("/queryFileBYId/{id}")
    public AjaxResult queryFileBYId(@PathVariable("id") Long id){
        if(ObjectUtils.isEmpty(id)){
            return AjaxResult.error("对应的id不能为空！");
        }
        return sysFileService.selectFileById(id);
    }


    /**
     * 根据文件id查询文件信息
     * @param id String
     * @return
     */
    @GetMapping("/getFileById/{id}")
    public AjaxResult getFileBYId(@PathVariable("id") String id){
        if(StringUtils.isEmpty(id)){
            return AjaxResult.error("对应的id不能为空！");
        }
        long lid = Long.parseLong(id);
        return sysFileService.selectFileById(lid);
    }

    /**
     * 删除文件接口
     * @param id
     * @return
     */
    @Log(title = "文件删除", businessType = BusinessType.DELETE)
    @GetMapping("/delete/{id}")
    public AjaxResult deleteFileById(@PathVariable("id") Long id){
        return sysFileService.delFileById(id);
    }

    /**
     * 修改文件接口
     * @param sysFiles
     * @return
     */
    @PostMapping("/update")
    public AjaxResult updateFile(@RequestBody SysFiles sysFiles){
        return sysFileService.updateSysFiles(sysFiles);
    }

    /**
     * 批量删除文件接口
     * @param list
     * @return
     */
    @PostMapping("/deleteBatchById")
    public AjaxResult deleteBatchFile(@RequestBody List<Long> list){
        try {
            if(CollectionUtils.isEmpty(list)){
                return AjaxResult.error("id列表不能为空");
            }
            for (Long aLong : list) {
                SysFiles byId = sysFileService.getById(aLong);
                byId.setDelFlag("2");
                byId.setUpdateTime(LocalDateTime.now());
                sysFileService.updateById(byId);
            }
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("删除异常");
        }
    }
    /**
     * 文件下载
     * */
    @Log(title = "文件下载", businessType = BusinessType.EXPORT)
    @GetMapping("/download/{id}")
    public void download(@PathVariable("id") Long id, HttpServletResponse response) throws Exception {
        sysFileService.downloadFile(id,response);
    }

//    /**
//     * PLM文件下载
//     * */
//    @Log(title = "PLM文件下载", businessType = BusinessType.EXPORT)
//    @GetMapping("/download/plm/{id}")
//    public void downloadPLMFile(@PathVariable("id") Long id, HttpServletResponse response) throws Exception {
//        sysFileService.downloadPLMFile(id,response);
//    }

    @Log(title = "批量上传文件",businessType = BusinessType.INSERT)
    @PostMapping("/batchUpload")
    @Transactional(rollbackFor = {Exception.class,RuntimeException.class})
    public AjaxResult batchUploadFile(@RequestParam("files") MultipartFile[] files,String type){
        try {
            List<SysFiles> filesList = sysFileService.BatchFileUpLoad(files, type, null);
            return AjaxResult.success(filesList);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("批量上传文件失败:"+ JSONObject.toJSONString(e));
            return AjaxResult.error("批量上传文件异常:"+e.getMessage());
        }
    }

    /**
     * 文件下载
     * */
    @Log(title = "文件下载_配置主键", businessType = BusinessType.EXPORT)
    @GetMapping("/downloadByConfig/{key}")
    public void downloadByConfig(@PathVariable("key") String key, HttpServletResponse response) throws Exception {
        sysFileService.getFileByConfig(key,response);
    }

}

